import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//通过过滤器来实现PC和移动端的切换
public class DriverFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String uri = request.getRequestURI();
        if (uri.startsWith("/PC")||uri.startsWith("/Mobile")){
            chain.doFilter(req,resp);
        } else {
            //获取Header中user-agent，也就是获取使用设备信息，并转化为小写单词
            String userAgent = request.getHeader("user-agent").toLowerCase();
            String targetURI = "";
            //匹配设备名
            if (userAgent.indexOf("andriod")==-1||userAgent.indexOf("iphone")==-1){
                targetURI = "/Mobile" + uri;
                System.out.println("移动端，uri："+uri);
                //重新想浏览器发送uri
                response.sendRedirect(targetURI);
            } else {
                targetURI = "/PC" + uri;
                System.out.println("PC端，uri："+uri);
                //重新想浏览器发送uri
                response.sendRedirect(targetURI);
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
